package gui;

import domain.DomainController;
import domain.GameGrid;
import domain.player.Disc;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import main.AppConstants;

/**
 *
 * @author Mattis
 */
public class SetDialog extends JDialog{
	private final static String EMPTY = "Empty", PLAYER1 = "Player 1", PLAYER2 = "Player 2";

	private JLabel[][] board = new JLabel[GameGrid.GRID_ROWS][GameGrid.GRID_COLUMNS];
	private GameGrid grid;

	public SetDialog(DomainController dc){
		grid = new GameGrid(dc);
                // grid = dc.getGameGrid();
		grid.resetGameGrid();

		setModal(true);
        setTitle("setBoard");

		Box box = Box.createVerticalBox();

        box.add(new BoardPanel());
		box.add(createOKButton());

		getContentPane().add(box);

		pack();

        setVisible(true);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
	}

	/*
    public SetDialog(){
        this(null);
    }
	*/

	private boolean checkBoard(){
		StringBuilder errorStr = new StringBuilder("<html><head></head><body><ul>");
		boolean error = false;
		String err;

		int pl1 = 0, pl2 = 0;

		for(int i = 0; i < GameGrid.GRID_COLUMNS; i++) {
			for(int j = GameGrid.GRID_ROWS-1; j > 0 ; j--) {
				if(board[j][i].getText() == PLAYER1)
					pl1++;
				else if(board[j][i].getText() == PLAYER2)
					pl2++;
				else if(board[j-1][i].getText() != EMPTY) {
					err = "<li> Empty spot in column " + (i+1) + ", from the left.<br />";
					errorStr.append(err);
					error = true;
				}
			}
		}
                System.out.println("nr of player1 " + pl1 + " nr of player2 " + pl2);
		errorStr.append("</ul>");

		if(pl2-pl1 > 1){
			err = "Player 2 has too many discs.<br />"
				+ "<ul><li>Player 1: " + pl1
				+ "<li>Player 2: " + pl2 + "</ul>";
			errorStr.append(err);
			error = true;
		}
		if(pl2-pl1 < 0){
			err = "Player 1 has too many discs.<br />"
				+ "<ul><li>Player 1: " + pl1
				+ "<li>Player 2: " + pl2 + "</ul>";
			errorStr.append(err);
			error = true;
		}

		errorStr.append("</body></html>");

		if(!error){
			return true;
		} else {
			new DebugDialog(errorStr.toString());
			//JOptionPane.ShowMessageDialog(null, error, "Error", JOptionPane.ERROR_MESSAGE);
			return false;
		}
	}

	private class BoardPanel extends JPanel{
		public BoardPanel(){
			this.setLayout(new GridLayout(GameGrid.GRID_ROWS, GameGrid.GRID_COLUMNS));
			addMouseListeners();
			setUpBoard();
			this.setVisible(true);
			this.setPreferredSize(new Dimension(600, 500));
			this.setMaximumSize(new Dimension(600, 500));
		}

		private void setUpBoard(){
			for(int i = 0; i < GameGrid.GRID_ROWS; i++){
				for(int j = 0; j < GameGrid.GRID_COLUMNS; j++){
					this.add(board[i][j]);
				}
			}
		}

		private void addMouseListeners(){
			for(int i = 0; i < GameGrid.GRID_ROWS; i++){
				for(int j = 0; j < GameGrid.GRID_COLUMNS; j++){
					board[i][j] = new JLabel();
					board[i][j].setHorizontalAlignment(SwingConstants.CENTER);
					board[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
				}
			}
			for(int i = 0; i < GameGrid.GRID_ROWS; i++){
				for(int j = 0; j < GameGrid.GRID_COLUMNS; j++){
					board[i][j].addMouseListener(new MouseClickListener(board[i][j]));
					board[i][j].setText("Empty");
				}
			}
		}
	}

	private class MouseClickListener extends MouseAdapter {
		JLabel boundTo;
		int nrOfClicks = 0;
		public MouseClickListener(JLabel boundTo) {
			this.boundTo = boundTo;
			this.boundTo.setOpaque(true); // used so the background color actually changes
		}

		@Override
		public void mouseClicked(MouseEvent e) {
			//System.out.println("mouse clicked");
			nrOfClicks++;
			//boundTo.setText("clicked");

			if(nrOfClicks % 3 == 1){
				boundTo.setText(PLAYER1);
				boundTo.setBackground(Color.RED);
			} else if(nrOfClicks % 3 == 2){
				boundTo.setText(PLAYER2);
				boundTo.setBackground(Color.YELLOW);
			} else{
				boundTo.setText(EMPTY);
				boundTo.setBackground(null);
			}
		}
	}

	private class DebugDialog extends JDialog {
		public DebugDialog(String msg){
			setModal(true);
			setLocationRelativeTo(null);
			setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			setLayout(new BorderLayout());

			setTitle("Error");

			this.add(new JLabel("  "), BorderLayout.WEST);
			this.add(new JLabel(msg), BorderLayout.CENTER);

			setSize(230, 330);

			//pack();
			setVisible(true);
		}
	}

	/** Add the OK button component to the dialog */
	private JPanel createOKButton() {
		JPanel buttonPanel = new JPanel(new FlowLayout());
		buttonPanel.setBackground(AppConstants.COLOR_PANEL_BACKGROUND);
		buttonPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, AppConstants.COLOR_PANEL_BORDER));

		// OK button:
		JButton jBtnOK = new JButton("OK");
		jBtnOK.setBackground(AppConstants.COLOR_PANEL_BACKGROUND);
		jBtnOK.addActionListener(new ActionListener() {

			/**
			 * Button listener: OK
			 * If there's valid data = create players otherwise show error dialog
			 */
			@Override
			public void actionPerformed(ActionEvent e) {
                            grid.resetGameGrid();
				if(checkBoard()){
                                    
                            // System.out.println("copying grid");
					for( int i = 0; i < GameGrid.GRID_ROWS; i++ ) {
						for( int j = 0; j < GameGrid.GRID_COLUMNS; j++ ) {
							if(board[i][j].getText().equals(PLAYER1))
								grid.setDiscAt(i, j, Disc.ONE);
							else if(board[i][j].getText().equals(PLAYER2))
								grid.setDiscAt(i, j, Disc.TWO);
							else
								grid.setDiscAt(i, j, Disc.NONE);
						}
                                                
						grid.getLogicController().setGameGrid(grid);
					}

					dispose();
				}
			}
		});
		buttonPanel.add(jBtnOK);
                grid.getLogicController().getGuiController().updateGameFrame();
		return buttonPanel;
	}
}